import { createRouter, createWebHistory } from 'vue-router';
import pinia from './pinia';
import { useUserStore } from '../store/user';

const user = useUserStore(pinia);

// 不需要权限的页面
const constantRoutes = [
  {
    // 登录
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  },
  {
    // 404
    path: '/:pathMatch(.*)',
    name: 'notFound',
    component: () => import('../views/error/notFound.vue')
  },
  {
    // 无权限
    path: '/noPermission',
    name: 'noPermission',
    component: () => import('../views/error/noPermission.vue')
  }
];

const asyncRoutes = {
  path: '/',
  name: 'main',
  component: () => import('../views/mainPage.vue'),
  children: [
    {
      // 首页
      path: '/',
      name: 'home',
      component: () => import('../views/home/index.vue')
    }
  ]
};

const router = createRouter({
  history: createWebHistory('/'),
  routes: constantRoutes
});

router.addRoute(asyncRoutes);

router.beforeEach((to, from, next) => {
  // 切换router时，取消pending中的请求
  if (window.__axiosPromiseArr) {
    window.__axiosPromiseArr.forEach((ele, ind) => {
      ele.cancel();
      delete window.__axiosPromiseArr[ind];
    });
  }
  // token过期时间
  if (localStorage.getItem('expires') && (new Date().getTime() - localStorage.getItem('expires')) / 1000 > 1) {
    $uiMsg.error('登录失效，请重新登录', () => {
      localStorage.removeItem('userInfon');
      localStorage.removeItem('token');
      localStorage.removeItem('expires');
      location.href = '/login';
    });
    return;
  }
  // 登录判断
  if (user.token) {
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
      // 权限判断
      next();
    }
  } else {
    if (to.path === '/login') {
      next();
    } else {
      next({ name: 'login' });
    }
  }
});

// 跳转完成后，将滚动条位置重置
router.afterEach(to => {
  window.scrollTo(0, 0);
});

export default router;
